package com.ch.fastbuilder.common;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ConnectionManager {
	 
    private static boolean initialized = false;
    private static final Log log = LogFactory.getLog(ConnectionManager.class);
    
    private static final ThreadLocal<DataSource> dataSource = new ThreadLocal<DataSource>();

    private ConnectionManager() {
        super();
    }

    public static Connection currentConnection() throws SQLException {
        Connection conn = LocalConnetionManager.getAutoConnection();
        if(conn == null) conn = LocalConnetionManager.getHandConnection();
        if(conn != null && !conn.isClosed()) return conn;
        
    	DataSource dataSource = LocalDataSourceManager.getDataSource();
    	if(dataSource == null) {
    		dataSource = DataSourceUtil.getDataSource();
    	}
    	
		conn = dataSource.getConnection();	
		conn.setAutoCommit(true);
        return conn;
    }
    
    public static DataSource currentDataSource() throws SQLException {
        DataSource dataSource = LocalDataSourceManager.getDataSource();
        if(dataSource == null) {
        	dataSource = DataSourceUtil.getDataSource();
        }
        
        return dataSource;
    }
    
    /**
     * 设置当前数据源，主要是供Model切换数据源使用，建议不要使用这种方式
     * @param dataSourceName
     * @return
     */
    public static DataSource setCurrentDataSource(String dataSourceName) {
    	DataSource ds = DataSourceUtil.getDataSource(dataSourceName);
    	dataSource.set(ds);
    	
        return ds;
    }
    
    public static void beginTransaction() throws SQLException {
        Connection conn = ConnectionManager.currentConnection();
        conn.setAutoCommit(false);
        LocalConnetionManager.setHandConnection(conn);
    }
}
